<template>
  <div class="picture-management">
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" @submit.prevent>
        <el-form-item label="图片名称">
          <el-input v-model="searchForm.searchQuery" placeholder="请输入图片关键字" clearable />
        </el-form-item>
        <el-form-item label="分类">
          <el-select
            v-model="searchForm.classifyId"
            placeholder="请选择图片分类"
            @change="onSearch"
          >
            <el-option label="全部" :value="null"></el-option>
            <el-option
              v-for="classify in classifyStore.classifies"
              :key="classify.id"
              :value="classify.id"
            >
              {{ classify.name }}
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="审核状态">
          <el-select v-model="searchForm.reviewStatus" placeholder="请选择" @change="onSearch">
            <el-option label="全部" :value="null" />
            <el-option label="待审核" :value="0" />
            <el-option label="通过" :value="1" />
            <el-option label="不通过" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="修改时间">
          <el-date-picker
            v-model="searchForm.date"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="onSearch"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSearch">查询</el-button>
          <el-button @click="onReset">重置</el-button>
          <el-button type="primary" @click="fetchDialogVisible = true">批量抓取图片</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="table-card">
      <el-table :data="pictures" border stripe>
        <el-table-column prop="thumbnailUrl" label="缩略图" width="100">
          <template #default="{ row }">
            <el-image
              style="width: 100px; height: 100px"
              :src="row.thumbnailUrl || row.url"
              :zoom-rate="1.2"
              :max-scale="7"
              :min-scale="0.2"
              :preview-src-list="[row.url]"
              fit="cover"
              :preview-teleported="true"
            />
          </template>
        </el-table-column>
        <el-table-column prop="name" label="名称" min-width="120" />
        <el-table-column label="分类" width="100">
          <template v-slot="{ row }">
            <text>{{
              classifyStore.classifies.find((item) => item.id === row.classifyId)?.name
            }}</text>
          </template>
        </el-table-column>
        <el-table-column prop="tags" label="标签" min-width="120">
          <template #default="{ row }">
            <el-tag v-for="tag in parseTags(row.tags)" :key="tag" class="tag">{{ tag }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="picFormat" label="格式" width="80" />
        <el-table-column prop="picSize" label="体积" width="100">
          <template #default="{ row }">
            {{ formatSize(row.picSize) }}
          </template>
        </el-table-column>
        <el-table-column prop="reviewStatus" label="审核状态" width="100">
          <template #default="{ row }">
            <el-tag v-if="row.reviewStatus === 0" type="warning">待审核</el-tag>
            <el-tag v-if="row.reviewStatus === 1" type="success">通过</el-tag>
            <el-tag v-if="row.reviewStatus === 2" type="danger">不通过</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220">
          <template #default="{ row }">
            <el-button size="small" @click="onEdit(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="onDelete(row)">删除</el-button>
            <el-button size="small" type="success" @click="onReview(row)">审核</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页插件 -->
      <el-pagination
        class="pagination"
        :current-page="searchForm.pageNum"
        :page-size="searchForm.pageSize"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @current-change="
          (val) => {
            searchForm.pageNum = val
            getPictureList()
          }
        "
        @size-change="
          (val) => {
            searchForm.pageSize = val
            getPictureList()
          }
        "
      />
    </el-card>

    <!-- 编辑弹窗 -->
    <el-dialog v-model="editDialogVisible" title="编辑图片" width="400px">
      <el-form :model="editForm" label-width="80px">
        <el-form-item label="名称">
          <el-input v-model="editForm.name" />
        </el-form-item>
        <el-form-item label="简介">
          <el-input v-model="editForm.introduction" type="textarea" />
        </el-form-item>
        <el-form-item label="分类">
          <!-- 选择分类 -->
          <el-select v-model="editForm.classifyId" placeholder="请选择分类">
            <el-option
              v-for="item in classifyStore.classifies"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="标签">
          <!-- 标签栏 -->
          <el-select
            v-model="editForm.tags"
            multiple
            filterable
            allow-create
            default-first-option
            placeholder="请输入标签"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="onEditSave">保存</el-button>
      </template>
    </el-dialog>

    <!-- 审核弹窗 -->
    <el-dialog v-model="reviewDialogVisible" title="审核图片" width="400px">
      <el-form :model="reviewForm" label-width="80px">
        <el-form-item label="审核结果">
          <el-radio-group v-model="reviewForm.status">
            <el-radio :label="1">通过</el-radio>
            <el-radio :label="2">不通过</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="审核信息">
          <el-input v-model="reviewForm.message" type="textarea" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="reviewDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="onReviewSave">提交</el-button>
      </template>
    </el-dialog>

    <!-- 批量抓取图片 -->
    <el-dialog v-model="fetchDialogVisible" title="批量抓取图片" width="400px">
      <el-form :model="fetchForm" label-width="80px">
        <el-form-item label="关键字">
          <el-input v-model="fetchForm.keyword" placeholder="请输入关键字" />
        </el-form-item>
        <el-form-item label="数量">
          <el-input-number v-model="fetchForm.count" :min="1" :max="5" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="fetchDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="fetching" @click="onFetch">开始抓取</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getPictureListAdminAPI,
  updatePictureAPI,
  deletePictureAPI,
  reviewPictureAPI,
  batchFetchPicturesAPI,
} from '@/api/pictureAPI'
import { useUserStore } from '@/stores/user'
import { useClassifyStore } from '@/stores/classify'
import dayjs from 'dayjs'

const userStore = useUserStore()
const classifyStore = useClassifyStore()
const userId = userStore.userInfo.id

// 模拟图片数据
const pictures = ref([])

const searchForm = reactive({
  name: '',
  classifyId: null,
  reviewStatus: null,
  pageNum: 1,
  pageSize: 10,
  searchQuery: '',
  date: [],
})

const total = ref(0)

const fetching = ref(false) // 是否正在抓取图片

const getPictureList = async () => {
  console.log('获取图片列表参数:', searchForm)
  const startEditTime = searchForm.date[0]
    ? dayjs(searchForm.date[0]).format('YYYY/MM/DD HH:mm:ss')
    : null
  const endEditTime = searchForm.date[1]
    ? dayjs(searchForm.date[1]).format('YYYY/MM/DD HH:mm:ss')
    : null
  console.log('开始时间:', startEditTime, '结束时间:', endEditTime)

  const res = await getPictureListAdminAPI({
    pageNum: searchForm.pageNum,
    pageSize: searchForm.pageSize,
    searchQuery: searchForm.searchQuery,
    reviewStatus: searchForm.reviewStatus,
    classifyId: searchForm.classifyId,
    startEditTime,
    endEditTime,
  })
  console.log('获取图片列表:', res)

  if (res.code === 200) {
    pictures.value = res.data.records
    total.value = res.data.total
  } else {
    ElMessage.error('获取图片列表失败')
  }
}

const onSearch = () => {
  searchForm.pageNum = 1
  getPictureList()
}

const onReset = () => {
  searchForm.name = ''
  searchForm.classifyId = ''
  searchForm.reviewStatus = null
  searchForm.pageNum = 1
  searchForm.pageSize = 10
  searchForm.searchQuery = ''
  getPictureList()
}

const parseTags = (tags) => {
  try {
    return JSON.parse(tags)
  } catch {
    return []
  }
}

const formatSize = (size) => {
  if (!size) return '0B'
  if (size < 1024) return size + 'B'
  if (size < 1024 * 1024) return (size / 1024).toFixed(1) + 'KB'
  return (size / 1024 / 1024).toFixed(1) + 'MB'
}

// 编辑相关
const editDialogVisible = ref(false)
const editForm = reactive({
  id: null,
  name: '',
  introduction: '',
  classifyId: '',
  tags: [],
  url: '',
})

const onEdit = (row) => {
  editForm.id = row.id
  editForm.name = row.name
  editForm.introduction = row.introduction
  editForm.classifyId = row.classifyId
  editForm.tags = parseTags(row.tags)
  editForm.url = row.url
  editDialogVisible.value = true
}

const onEditSave = async () => {
  await updatePictureAPI({
    id: editForm.id,
    name: editForm.name,
    introduction: editForm.introduction,
    classifyId: editForm.classifyId,
    tags: editForm.tags,
    userId: userId,
    url: editForm.url,
  })

  ElMessage.success('编辑成功')
  getPictureList()
  editDialogVisible.value = false
}

// 删除
const onDelete = (row) => {
  ElMessageBox.confirm('确定要删除该图片吗？', '提示', {
    type: 'warning',
  })
    .then(async () => {
      await deletePictureAPI({
        id: row.id,
      })
      getPictureList()
      ElMessage.success('删除成功')
    })
    .catch(() => {
      ElMessage.info('已取消删除')
    })
}

// 审核相关
const reviewDialogVisible = ref(false)
const reviewForm = reactive({
  id: null,
  status: 1,
  message: '',
})
let reviewingRow = null

const onReview = (row) => {
  reviewingRow = row
  reviewForm.id = row.id
  reviewForm.status = row.reviewStatus
  reviewForm.message = row.reviewMessage || ''
  reviewDialogVisible.value = true
}

/**
 * 审核保存
 */
const onReviewSave = async () => {
  if (reviewingRow) {
    await reviewPictureAPI({
      id: reviewForm.id,
      reviewStatus: reviewForm.status,
      reviewMessage: reviewForm.message,
    })
    ElMessage.success('审核完成')
    getPictureList()
    reviewDialogVisible.value = false
  }
}

// 批量抓取图片相关
const fetchDialogVisible = ref(false)
const fetchForm = reactive({
  keyword: '',
  count: 5,
})

const onFetch = () => {
  if (!fetchForm.keyword) {
    ElMessage.warning('请输入关键字')
    return
  }
  // 等待响应动画
  ElMessage.info('正在抓取图片，请稍候...')
  fetching.value = true
  batchFetchPicturesAPI({
    searchText: fetchForm.keyword,
    batchNum: fetchForm.count,
  })
    .then((res) => {
      if (res.code === 200) {
        ElMessage.success(`成功抓取 ${res.data} 张图片`)
        getPictureList()
      } else {
        ElMessage.error('抓取图片失败，请稍后再试')
      }
    })
    .catch(() => {
      ElMessage.error('抓取图片失败，请稍后再试')
    })
    .finally(() => {
      getPictureList()
      fetching.value = false
      fetchDialogVisible.value = false
    })
}

onMounted(() => {
  getPictureList()
})
</script>

<style scoped>
.picture-management {
  padding: 24px;
  background: #f5f7fa;
  min-height: 100vh;
}
.search-card {
  margin-bottom: 18px;
}
.table-card {
  margin-top: 0;
}
.tag {
  margin-right: 4px;
}
</style>
